<?php
/**
 * Copyright (c) 2013 pipapai.com
 */
JLoader::register("PJobSeekerModelJobSeeker", OC::$SERVERROOT."/apps/jobseeker/lib/jobseeker.php");
JLoader::register("PJobSeekerModelPassword", OC::$SERVERROOT."/apps/jobseeker/lib/password.php");
JLoader::register("PInterviewModelInterview", OC::$SERVERROOT."/apps/interview/lib/interview.php");

class PJobSeekerController {
   public static function home() {
      if(!PUtil::checkUserLogin(false))
         return;

      $user = PFactory::getUser();

      // as we share sessions between blog/support with main domain, for certain type of users, 
      // we need to do proper redirect as editor now is jobseeker too 
      if(hasEditorAccess($user)) {
         OC_Response::redirect(OC_Request::serverProtocol() . "://blog." . PUtil::serverDomain());
         return; 
      }

      $model = new PJobSeekerModelJobSeeker();
      $needjobs = $model->needJob($user->email,$user->id);

      $tmpl = new OCP\Template('jobseeker', 'home', 'user');
      $tmpl->assign('needjobs', $needjobs);
      $tmpl->assign('page_title', '应聘管理');
      $tmpl->printPage();
   }
   
   public static function registers() {
      if(OC_User::isLoggedIn()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      if(PUtil::needSSL()) {
         OC_Response::redirect(PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("jobseeker_registers")));
         return;
      }

      $app = PFactory::getApplication();
      $token = $app->getUserState("interview_token");
      $has_verified_token = $app->getUserState("has_verified_token_".$token);

      $tmpl = new OCP\Template('jobseeker', 'registers', 'base');
      $tmpl->assign('page_title', '用户注册');
      $tmpl->assign('is_jobseeker', true);

      //# registers from interview
      if(!empty($token)) {
          if (!$has_verified_token) {
              OC_Response::redirect(OC_Helper::linkToRoute("interview_home", array('token'=>$token)));
              return;
          } else {
              $model = new PInterviewModelInterview();
              $basicInfo = $model->getJobseekerBasicInfo($token);
              $app->setUserState("jobseeker_registers_basicinfo",$basicInfo);
              $tmpl->assign('jobseeker_name', $basicInfo->jobseeker_name);
              $tmpl->assign('jobseeker_email', $basicInfo->jobseeker_email);
              $tmpl->assign('has_verified_token', $has_verified_token);
          }
      }

      $tmpl->printPage();
   }

   public static function postlogin() {
      OC_JSON::setContentTypeHeader();
      $app = PFactory::getApplication();
      $return = $app->getUserState("return");
      $app->setUserState("return", "");
      if(OC_User::isLoggedIn()) {
         jexit(jsonSuccess('success', (!empty($return) ? $return : OC_Helper::linkToRoute("jobseeker_home")), null, false));
      }

      /* perform the login */
      $app = PFactory::getApplication();
      $model = new PJobSeekerModelJobSeeker();
      if(!$model->login()) {
         $failtimes = $app->getUserState("login_failed_times", 0);
         $failtimes++;
         $app->setUserState("login_failed_times", $failtimes);
         if($failtimes>3) {
            $app->setUserState("login_failed_captcha", true);
            jexit(jsonError($model->getError(),  array('captcha'=>1), false));
         } else
         jexit(jsonError($model->getError(), null, false));
      }

      // login is fine, reset login_failed_times
      $app->setUserState("login_failed_times", 0);
      $app->setUserState("login_failed_captcha", false);

      $return = JArrayHelper::getValue($post, 'return', '');

      if (!PFactory::isJobseekerUser())
         $redirect_url = PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("company_home"));
      else
         $redirect_url = !empty($return) ? $return : PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("jobseeker_home"));

      jexit(jsonSuccess('success', $redirect_url, null, false));
   }

   // censor reg username
   public static function validatename() {
      OC_JSON::setContentTypeHeader();

      $name = JRequest::getString("name", null);

      $message = CensorHelper::validateName($name);
      if($message === true) {
         jexit(json_encode(true));
      } else
         jexit(json_encode($message));
   }

   // validemail
   public static function validateemail() {
      OC_JSON::setContentTypeHeader();

      $email = JRequest::getString("email", null);

      $message = JobHelper::validateEmail($email);
      if($message === true)
         jexit(json_encode(true));
      else
         jexit(json_encode($message));
   }

   //# join from interview
   public static function join() {
       $app = PFactory::getApplication();
       $token = $app->getUserState("interview_token");
       $has_verified_token = $app->getUserState("has_verified_token_".$token);
       if ($has_verified_token) {
           $model = new PJobSeekerModelJobSeeker();
           $email = $model->join($token);

           if(!empty($email['email'])){
               OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_login"));
               return;
           }else{
               OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_registers"));
               return;
           }
       }
       OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home", array('token'=>$token)));
       return;
   }

   public static function saveregemp() {
      if(OC_User::isLoggedIn())
         jexit();

      $app =  PFactory::getApplication();

      OC_JSON::setContentTypeHeader();
      $model = new PJobSeekerModelJobSeeker();
      $jobseeker = $model->register();
      if(!$jobseeker) {
         // enable captch if it failed too many times
         $failtimes = $app->getUserState("register_failed_times", 0);
         $failtimes++;
         $app->setUserState("register_failed_times", $failtimes);
         if($failtimes>3) {
            $app->setUserState("register_failed_captcha", true);
            jexit(jsonError($model->getError(),  array('captcha'=>1), false));
         } else {
            jexit(jsonError($model->getError(), null, false));
         }
      }

      /* the registration is success if we reach here */
      jexit(jsonSuccess('注册成功！', null, null, false));
   }
   
   public static function settings() {
      if(!PUtil::checkUserLogin(false))
         return;

      if(!PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
            
      $user = PFactory::getUser();

      $tmpl = new OCP\Template('jobseeker', 'changepassword', 'user');
      $tmpl->assign('page_title', '修改密码');
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function setpassword() {
       OC_JSON::setContentTypeHeader();
       if(!OC_User::isLoggedIn()) {
           jexit(jsonError('请先登录', null, false));
       }
   
       $model = new PJobSeekerModelJobSeeker();
       if(!$model->saveSettings()) {
           jexit(jsonError($model->getError(), null, false));
       }
   
       jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function setpersontest(){
       OC_JSON::setContentTypeHeader();
       if(!OC_User::isLoggedIn()) {
           jexit(jsonError('请先登录', null, false));
       }
        
       $model = new PJobSeekerModelJobSeeker();
       if(!$model->setpersontest()) {
           jexit(jsonError('保存失败', null, false));
       }
        
       jexit(jsonSuccess('保存成功！', null, null, false));       
   }


   public static function login() {
      $app = PFactory::getApplication();
      $return = $app->getUserState("return");
      $app->setUserState("return", "");

      if(OC_User::isLoggedIn()) {
         OC_Response::redirect(!empty($return) ? $return : OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      if(PUtil::needSSL()) {
         // Should restore $return into session again
         if(!empty($return)) $app->setUserState("return", $return);
         OC_Response::redirect(PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("jobseeker_login")));
         return;
      }

      $tmpl = new OCP\Template('jobseeker', 'login', 'base');
      $tmpl->assign('page_title', '用户登录');
      $tmpl->assign('return', $return);
      $tmpl->assign('is_jobseeker', true);
      $tmpl->printPage();
   }

   public static function logout() {
      $model = new PCompanyModelCompany();
      $model->logout();
   }

   public static function lostpassword() {
      $tmpl = new OCP\Template('jobseeker', 'lostpassword', 'base');
      $tmpl->assign('page_title', '忘记密码?');
      $tmpl->assign('is_jobseeker', true);
      $tmpl->printPage();
   }

   public static function sendpassreset() {
      OC_JSON::setContentTypeHeader();
      $model = new PJobSeekerModelPassword();

      if(!$model->sendPassReset()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess("密码重置链接已经发送到您的邮箱。当您收到邮件，请重新登录。如果您没有收到, 请查看是否被转到了垃圾邮件文件夹。", null, null, false));
   }

   public static function passwdreset() {
      $model = new PJobSeekerModelPassword();

      $user = $model->getUserFromToken();
      if(!$user) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_login"));
         return;
      }

      $tmpl = new OCP\Template('jobseeker', 'passwdreset', 'base');
      $tmpl->assign('page_title', '密码重置');
      $tmpl->assign('is_jobseeker', true);
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function setnewpass() {

      OC_JSON::setContentTypeHeader();
      $model = new PJobSeekerModelPassword();
      if(!$model->setNewPass()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('密码设置成功，请使用新密码登录。', null, null, false));
   }
   
   public static function managepersontest() {
      if(!PUtil::checkUserLogin(false))
         return;

      $user = PFactory::getUser();
      $model = new PJobSeekerModelJobSeeker();
      $jobseekerpersontest = $model->loadjobseekerpersontest();
      $tmpl = new OCP\Template('jobseeker', 'managepersontest', 'user');
      $tmpl->assign('page_title', '评测管理');
      $tmpl->assign('jobseekerpersontest', $jobseekerpersontest);
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

}
